/*
RetroLeague - Mobile application for The Retro League Podcast
Copyright (C) 2010-2013 Hugues Johnson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.retroleague;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class SettingsActivity extends SherlockActivity{
	private static final String TAG="SettingsActivity";
	//menu constants
	private final static int MENU_BACK=0;
	//shared UI components
	private EditText editTextTimeout;
	private EditText editTextRefreshInterval;
	private CheckBox checkboxFacebook;
	private CheckBox checkboxForums;
	private CheckBox checkboxGooglePlus;
	private CheckBox checkboxHJ;
	private CheckBox checkboxTumblr;
	private CheckBox checkboxTwitter;
	private CheckBox checkboxYoutube;

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		try{
			//load the view
			this.setContentView(R.layout.settingslayout);
			//setup actionbar
			ActionBar actionBar=getSupportActionBar();
			actionBar.setIcon(R.drawable.logo); 
			actionBar.setTitle("");
			//setup UI events
			this.editTextTimeout=(EditText)findViewById(R.id.settings_timeout);
			this.editTextTimeout.addTextChangedListener(new TextWatcher(){
				public void afterTextChanged(Editable e){
					try{
						int newValue=Integer.parseInt(editTextTimeout.getText().toString());
						saveTimeout(newValue);
					}catch(Exception x){
						Log.e(TAG,"afterTextChanged",x);
					}
				}
				public void beforeTextChanged(CharSequence s, int start, int count, int after){/*not implemented*/}
				public void onTextChanged(CharSequence s, int start, int before, int count){/*not implemented*/}
			});
			this.editTextRefreshInterval=(EditText)findViewById(R.id.settings_refreshinterval);
			this.editTextRefreshInterval.addTextChangedListener(new TextWatcher(){
				public void afterTextChanged(Editable e){
					try{
						int newValue=Integer.parseInt(editTextRefreshInterval.getText().toString());
						saveRefreshInterval(newValue);
					}catch(Exception x){
						Log.e(TAG,"afterTextChanged",x);
					}
				}
				public void beforeTextChanged(CharSequence s, int start, int count, int after){/*not implemented*/}
				public void onTextChanged(CharSequence s, int start, int before, int count){/*not implemented*/}
			});
			this.checkboxFacebook=(CheckBox)findViewById(R.id.settings_checkbox_facebook);
			this.checkboxFacebook.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_facebook),isChecked);
				}
			});
			this.checkboxForums=(CheckBox)findViewById(R.id.settings_checkbox_forums);
			this.checkboxForums.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_forums),isChecked);
				}
			});
			this.checkboxGooglePlus=(CheckBox)findViewById(R.id.settings_checkbox_googleplus);
			this.checkboxGooglePlus.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_googleplus),isChecked);
				}
			});
			this.checkboxHJ=(CheckBox)findViewById(R.id.settings_checkbox_hj);
			this.checkboxHJ.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_hj),isChecked);
				}
			});
			this.checkboxTumblr=(CheckBox)findViewById(R.id.settings_checkbox_tumblr);
			this.checkboxTumblr.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_tumblr),isChecked);
				}
			});
			this.checkboxTwitter=(CheckBox)findViewById(R.id.settings_checkbox_twitter);
			this.checkboxTwitter.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_twitter),isChecked);
				}
			});
			this.checkboxYoutube=(CheckBox)findViewById(R.id.settings_checkbox_youtube);
			this.checkboxYoutube.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					saveSource(getString(R.string.prefkey_show_youtube),isChecked);
				}
			});
		}catch(Exception x){
			Log.e(TAG,"onCreate()",x);
			TextView errorView=new TextView(this);
			errorView.setText(x.getMessage());
			this.setContentView(errorView);
		}
	}	
	
	@Override
	protected void onResume(){
		super.onResume();
		try{
			SharedPreferences prefs=this.getApplicationContext().getSharedPreferences("com.huguesjohnson.retroleague",MODE_PRIVATE);
			int timeout=prefs.getInt(getString(R.string.prefkey_timeout),5000);
			this.editTextTimeout.setText(Integer.toString(timeout));
			int refreshInterval=prefs.getInt(getString(R.string.prefkey_refresh_interval),15);
			this.editTextRefreshInterval.setText(Integer.toString(refreshInterval));
			this.checkboxFacebook.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_facebook),true));
			this.checkboxForums.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_forums),false));
			this.checkboxGooglePlus.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_googleplus),true));
			this.checkboxHJ.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_hj),true));
			this.checkboxTumblr.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_tumblr),true));
			this.checkboxTwitter.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_twitter),true));
			this.checkboxYoutube.setChecked(prefs.getBoolean(getString(R.string.prefkey_show_youtube),true));
		}catch(Exception x){
			Log.e(TAG,"onResume",x);
			showErrorDialog(x);
		}
	}	
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		try{
			menu.add(0,MENU_BACK,MENU_BACK,"Back to stream").setIcon(R.drawable.menu_back);
			return(true);
		}catch(Exception x){
			Log.e(TAG,"onCreateOptionsMenu",x);
			return(false);
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		try{
			switch(item.getItemId()){
			case MENU_BACK:{this.finish();return(true);}
			default:{return(false);}
			}
		}catch(Exception x){
			if(item!=null){
				Log.e(TAG,"onOptionsItemSelected: item.getItemId()="+item.getItemId(),x);
			}else{
				Log.e(TAG,"onOptionsItemSelected: item is null",x);
			}
			return(false);
		}
	}
	
	private void saveSource(String source,boolean newValue){
		try{
			SharedPreferences prefs=this.getApplicationContext().getSharedPreferences("com.huguesjohnson.retroleague",MODE_PRIVATE);
			SharedPreferences.Editor editor=prefs.edit(); 
			editor.putBoolean(source,newValue); 
			editor.commit(); 
		}catch(Exception x){
			Log.e(TAG,"saveSource, source="+source,x);
			showErrorDialog(x);
		}
	}
	
	private void saveTimeout(int newValue){
		try{
			SharedPreferences prefs=this.getApplicationContext().getSharedPreferences("com.huguesjohnson.retroleague",MODE_PRIVATE);
			SharedPreferences.Editor editor=prefs.edit(); 
			editor.putInt(getString(R.string.prefkey_timeout),newValue); 
			editor.commit(); 
		}catch(Exception x){
			Log.e(TAG,"saveTimeout, newValue="+newValue,x);
			showErrorDialog(x);
		}
	}	

	private void saveRefreshInterval(int newValue){
		try{
			SharedPreferences prefs=this.getApplicationContext().getSharedPreferences("com.huguesjohnson.retroleague",MODE_PRIVATE);
			SharedPreferences.Editor editor=prefs.edit(); 
			editor.putInt(getString(R.string.prefkey_refresh_interval),newValue); 
			editor.commit(); 
		}catch(Exception x){
			Log.e(TAG,"saveTimeout, newValue="+newValue,x);
			showErrorDialog(x);
		}
	}	
	
	private void showErrorDialog(Exception x){
		try{
	        new AlertDialog.Builder(this)
	   		.setTitle(R.string.app_name)
	   		.setMessage("Error: "+x.getMessage())
	   		.setPositiveButton("Close", null)
	   		.show();	
		}catch(Exception reallyBadTimes){
			Log.e(TAG,"showErrorDialog",reallyBadTimes);
		}
	}	
}